package com.lunm.im.server;

import com.lunm.im.factory.HandlerFactory;
import com.lunm.im.protocol.IMLengthFieldBasedFrameDecoder;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;

/**
 * RPC是远程过程调用（Remote Procedure Call）的缩写形式
 *
 * @version 1.0.0
 * @Author shawn
 * @Date 2024/12/31 8:55
 */
@Slf4j
public class RpcServer {
    public static void main(String[] args) {
        NioEventLoopGroup boss = new NioEventLoopGroup();
        NioEventLoopGroup worker = new NioEventLoopGroup();

        try {
            Channel channel = new ServerBootstrap()
                    .group(boss, worker)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) {
                            ch.pipeline().addLast(new IMLengthFieldBasedFrameDecoder());
                            ch.pipeline().addLast(HandlerFactory.getLoggingHandler());
                            ch.pipeline().addLast(HandlerFactory.getMessageCodec());
                            ch.pipeline().addLast(HandlerFactory.getRpcRequestHandler());
                        }
                    }).bind(8080).sync().channel();
            channel.closeFuture().sync();
        } catch (InterruptedException e) {
            log.error("server error", e);
        } finally {
            boss.shutdownGracefully();
            worker.shutdownGracefully();
        }
    }
}
